<html>
<head>

<title>Groovy Goodness: Traversing a Directory</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Traversing a Directory</h3>

<div class="post">
<p>Groovy adds the <code>traverse()</code> method to the <code>File</code> class in version 1.7.2. We can use this method to traverse a directory tree and invoke a closure to process the files and directories. If we look at the documentation we see we can also pass a map with a lot of possible options to influence the processing.</p>
<pre class="brush:groovy">
import static groovy.io.FileType.*
import static groovy.io.FileVisitResult.*

def groovySrcDir = new File(System.env['GROOVY_HOME'], 'src/')

def countFilesAndDirs = 0
groovySrcDir.traverse {
    countFilesAndDirs++
}
println "Total files and directories in ${groovySrcDir.name}: $countFilesAndDirs"

def totalFileSize = 0
def groovyFileCount = 0
def sumFileSize = { 
    totalFileSize += it.size()
    groovyFileCount++
}
def filterGroovyFiles = ~/.*\.groovy$/
groovySrcDir.traverse type: FILES, visit: sumFileSize, nameFilter: filterGroovyFiles
println "Total file size for $groovyFileCount Groovy source files is: $totalFileSize"

def countSmallFiles = 0
def postDirVisitor = {
    if (countSmallFiles > 0) {
     println "Found $countSmallFiles files with small filenames in ${it.name}"
 }
    countSmallFiles = 0
}
groovySrcDir.traverse(type: FILES, postDir: postDirVisitor, nameFilter: ~/.*\.groovy$/) {
    if (it.name.size() < 15) {
     countSmallFiles++
    }
}
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>